package com.vdong.common.oauth.common.util;


import com.alibaba.fastjson.JSON;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.config.AuthorizerApiConfig;
import com.github.sd4324530.fastweixin.api.config.ComponentApiConfig;
import com.github.sd4324530.fastweixin.servlet.WeixinSupport;
import com.vdongchina.boot.wechat.aes.AesException;
import com.vdongchina.boot.wechat.aes.MsgCrypt;

import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author 22990
 */
public abstract class AbstractOpenPlatformSupport extends WeixinSupport {
    private static final Logger logger = Logger.getLogger(AbstractOpenPlatformSupport.class);

    public AbstractOpenPlatformSupport() {
    }

    protected abstract String getSecret();

    protected abstract RedisTemplate getRedisTemplate();

    public MsgCrypt getMsgCrypt() throws AesException {
        MsgCrypt msgCrypt = new MsgCrypt(this.getToken(), this.getAESKey(), this.getAppId());
        return msgCrypt;
    }

    public void notifyReceive(String msgSignature, String timestamp, String nonce, HttpServletRequest request) {
        try {
            String postData = IOUtils.toString(request.getInputStream(), "utf-8");
            postData = this.getMsgCrypt().decryptAuth(msgSignature, timestamp, nonce, postData);
            Document doc = DocumentHelper.parseText(postData);
            Element rootElt = doc.getRootElement();
            String infoType = rootElt.elementText("InfoType");
            if (StringUtils.isBlank(infoType)) {
                return;
            }
            String componentVerifyTicket = "component_verify_ticket";
            String authorized = "authorized";
            String updateauthorized = "updateauthorized";
            String unauthorized = "unauthorized";
            if (componentVerifyTicket.equals(infoType)) {
                String ticket = rootElt.elementText("ComponentVerifyTicket");
                this.getRedisTemplate().opsForValue().set("fx_wxTicket", ticket);
                logger.debug("------------ticket：" + ticket);
                this.getTicket(ticket);
            } else if (authorized.equals(infoType)) {
                this.authorized(rootElt.elementText("AuthorizerAppid"), rootElt.elementText("AuthorizationCode"));
            } else if (updateauthorized.equals(infoType)) {
                this.updateAuthorized(rootElt.elementText("AuthorizerAppid"), rootElt.elementText("AuthorizationCode"));
            } else if (unauthorized.equals(infoType)) {
                this.unAuthorized(rootElt.elementText("AuthorizerAppid"));
            }
        } catch (Exception var10) {
            var10.printStackTrace();
        }

    }

    public ComponentApiConfig getComponentApiConfig() {
        String fxWxTicket = "fx_wxTicket";
        String fxComponentApiConfig = "fx_componentApiConfig";
        if (this.getRedisTemplate().opsForValue().get(fxWxTicket) != null) {
            String wxTicket = this.getRedisTemplate().opsForValue().get("fx_wxTicket").toString();
            ComponentApiConfig config;
            if (this.getRedisTemplate().opsForValue().get(fxComponentApiConfig) == null) {
                config = new ComponentApiConfig(this.getAppId(), this.getSecret(), wxTicket);
            } else {
                config = (ComponentApiConfig) this.getRedisTemplate().opsForValue().get("fx_componentApiConfig");
                config.setComponentVerifyTicket(wxTicket);
                config.getAccessToken();
            }

            this.getRedisTemplate().opsForValue().set("fx_componentApiConfig", config);
            return config;
        } else {
            return null;
        }
    }

    public String getPreAuthCode() {
        ComponentApiConfig config = this.getComponentApiConfig();
        logger.info("config:" + JSON.toJSONString(config));
        String preAuthCode = config.getPreAuthCode();
        this.getRedisTemplate().opsForValue().set("fx_componentApiConfig", config);
        return preAuthCode;
    }

    public AuthorizerApiConfig getAuthorizerApiConfig(String authorizerAppid, String refreshToken) {
        String key = "authorizerApiConfig_".concat(authorizerAppid);
        ComponentApiConfig componentApiConfig = this.getComponentApiConfig();
        AuthorizerApiConfig config;
        if (this.getRedisTemplate().opsForValue().get(key) == null) {
            config = new AuthorizerApiConfig(componentApiConfig.getAccessToken(), this.getAppId(), authorizerAppid, refreshToken, true);
        } else {
            config = (AuthorizerApiConfig) this.getRedisTemplate().opsForValue().get(key);
            config.setComponentAccessToken(componentApiConfig.getAccessToken());
            config.setRefreshToken(refreshToken);
            config.getAccessToken();
        }

        this.getRedisTemplate().opsForValue().set(key, config);
        return config;
    }

    public ApiConfig getApiConfig(String appid, String secret) {
        String key = "kpay:wechat:ApiConfig:".concat(appid);
        ApiConfig config;
        if (this.getRedisTemplate().opsForValue().get(key) == null) {
            config = new ApiConfig(appid, secret, true);
        } else {
            config = (ApiConfig) this.getRedisTemplate().opsForValue().get(key);
            config.setSecret(secret);
            config.getAccessToken();
        }

        this.getRedisTemplate().opsForValue().set(key, config, 2L, TimeUnit.HOURS);
        return config;
    }

    protected void getTicket(String ticket) {
    }

    protected void authorized(String appid, String code) {
    }

    protected void updateAuthorized(String appid, String code) {
    }

    protected void unAuthorized(String appid) {
    }
}
